<?php
namespace App\Listeners;

use App\Events\In\GiftBillingFinished;
use App\Events\Out\EventInviteOneOnOneShareAccepted;
use App\Models\InviteOneOnOneAcceptance;
use App\Models\InviteOneOnOneShare;
use App\Facades\KafkaBridge;
use Carbon\Carbon;

class OnGiftBillingFinished
{
    public function handle(GiftBillingFinished $event)
    {
        //记录领取，发送模板消息给分享人
        $referencePre = 'OneOnOne-';
        $referenceCode = $event->referenceCode;
        if(strpos($referenceCode, $referencePre) === false) {
            return;
        }
        $shareCode = str_replace($referencePre, '', $referenceCode);

        /**
         * @var InviteOneOnOneShare $share
         * @var InviteOneOnOneAcceptance $acceptance
         */
        $share = InviteOneOnOneShare::where('share_code', $shareCode)->first();
        if (empty($share)) {
            return ;
        }

        $share->increaseAcceptNum();
        if ($share->getAcceptNum() == InviteOneOnOneShare::TOTAL_NUM) {
            $share->setStatus(InviteOneOnOneShare::STATUS_DONE);
        }
        $share->save();

        $acceptance = new InviteOneOnOneAcceptance();
        $acceptance->setShareId($share->getId());
        $acceptance->setStudentId($event->studentId);
        $acceptance->save();

        $inviteEvent = new EventInviteOneOnOneShareAccepted();
        $inviteEvent->studentId = $event->studentId;
        KafkaBridge::push($inviteEvent);
    }
}